const express = require('express');
const app = express();

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')


let tk = {
    TOKEN_KEY: 'dsxing',
    TIME: 60 * 60 * 24
}

//随机字符串
const salt = bcrypt.genSaltSync(10)



// 让express识别从客户端提交过来的json
app.use(express.json())

//允许跨域
app.use(require('cors')())

// const c=require('cors');
// const cors=c();
// app.use(cors);

const connection = require('./db.js')
app.use(require('./roles.js'))

//登录
app.post('/api/login', async (req, res) => {
    let { userName, userPwd } = req.body;
    // let sql = "select * from users where username=? and password=?"
    let sql2 = "select password from users where username=?";
    try {
        connection.query(sql2, userName, (err, result) => {
            if (err) {
                res.send({
                    meta: {
                        msg: err,
                        status: 404
                    }
                })
            }
            else {
                
                if (!result || result.length == 0) {
                    res.send({
                        meta: {
                            msg: '账户或密码错误！',
                            status: 400
                        }
                    })
                }
                else {
                    let isOk = bcrypt.compareSync(userPwd, result[0].password)
                    // let isOk=userPwd==result[0].password?true:false
                    console.log(isOk)
                    if (isOk) {
                        let token = jwt.sign({ userName }, tk.TOKEN_KEY, { expiresIn: tk.TIME });
                        res.send({
                            result,
                            meta: {
                                msg: '登录成功!',
                                status: 200,
                                token: token
                            }
                        })
                    }
                    else{
                        res.send({
                            result,
                            meta: {
                                msg: '账户或密码错误！',
                                status: 400
                            }
                        })
                    }
                }
            }
        })
    }
    catch (e) {
        console.log(e)
    }
})


//注册账户
app.post('/api/register', async (req, res) => {
    const { userName, userPwd,phone,email,roles } = req.body;

    let sql = "select username from users where username=?";
    let sql2 = "insert into users(rid,username,password,mobile,email) values(?,?,?,?,?)";
    let sql3="select rid from roles where rname=?"
    // 密码加密
    let pwd = bcrypt.hashSync(userPwd, salt)

    connection.query(sql, userName, (err, result) => {
        if (!result || result.length == 0) {
            connection.query(sql3,roles,(err,result3)=>{
                console.log(result3)
                if(!result3||result3.length==0){
                    res.send({
                        meta:{
                            msg:"请选择角色身份",
                            status:401
                        }
                    })
                }
                else{
                    let rid=result3[0].rid;
                    connection.query(sql2, [rid,userName, pwd,phone,email], (err, result2) => {
                        if (err) {
                            res.send({
                                meta: {
                                    msg: err,
                                    status: 404
                                }
                            })
                        }
                        else {
                            res.send({
                                result2,
                                meta: {
                                    msg: '注册成功！',
                                    status: 200
                                }
                            })
                        }
                    })

                }
            })
            
        }
        else {
            res.send({
                meta: {
                    msg: '用户名已存在',
                    status: 400
                }
            })
        }
    })
})



//显示用户列表
app.get('/api/userList', async (rep, res) => {
    let sql = 'select u.id,r.rname,u.username,u.`password`,u.mobile,u.email from users u LEFT JOIN roles r on u.rid=r.rid';
    connection.query(sql, (err, result) => {
        if (err) {
            console.log("读取失败!");
            return
        }
        else {
            res.send(result);
        }
    })
})

//删除用户
app.delete('/api/userList/:id', async (rep, res) => {
    let sql = 'delete from users where id=?';
    let sqlParams = rep.params.id;
    connection.query(sql, sqlParams, (err) => {
        if (err) {
            console.log("删除用户失败!");
            return
        }
        else {
            res.send({
                status: true
            });
        }
    })

})

//获取需修改的数据
app.get('/api/userList/:id', async (req, res) => {
    let sql = 'select u.id,r.rname,u.username,u.`password`,u.mobile,u.email from users u LEFT JOIN roles r on u.rid=r.rid where id=?';
    let sqlParams = req.params.id;
    connection.query(sql, sqlParams, (err, result) => {
        if (err) {
            console.log("查询用户失败!");
            return
        }
        else {
            // console.log(result)
            res.send(result)
        }
    })

})

//修改数据
app.put('/api/userList/:id', async (req, res) => {
    let sql2='select rid from roles WHERE rname=?'
    let sql = 'update users set rid=?,password=?,mobile=?,email=? where id=?';
    let {password,email,mobile,roles}=req.body;
    let pwd = bcrypt.hashSync(password, salt)
    

    try{
        connection.query(sql2,roles,(err,result)=>{
            if (err) {
                console.log("修改用户失败!");
                return
            }
            else{
                if(!result||result.length==0){
                    res.send({
                        meta:{
                            msg:'请选择角色身份',
                            status:'401'
                        }
                    })
                }
                else{
                    let sqlParams = [result[0].rid,pwd,mobile,email,req.params.id];
                    // console.log(result[0].rid)
                    connection.query(sql, sqlParams, (err) => {
                        if (err) {
                            res.send({
                                meta:{
                                    msg:'修改失败',
                                    status:'404'
                                }
                            });
                        }
                        else {
                            res.send({
                                meta:{
                                    msg:'修改成功',
                                    status:'200'
                                }
                            });
                        }
                    })
                }
            }
        })
    }
    catch(e){
        console.log(e)
    }
    

    
    
})



app.get('/', async (req, res) => {
    res.send('index')
})


app.listen('3301', () => {
    console.log('http://localhost:3301/')
})